package com.xml.dom.read;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLScanner {
	
	private Document doc;
	
	/**
	 * Constructor
	 * @param path
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public XMLScanner(String path) throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		doc = builder.parse(new File(path));
	}
	
	/**
	 * scanning from xmldata
	 * @return List<BookDTO> 
	 */
	public List<BookDTO> scan() {
		List<BookDTO> bookList = null;
		Element books = doc.getDocumentElement();
		NodeList bookNodes = books.getChildNodes();
		if(null != bookNodes && bookNodes.getLength() > 0) {
			bookList = new ArrayList<BookDTO>();
			for(int i=0; i<bookNodes.getLength(); i++) {
				BookDTO book = getDTOFromNode(bookNodes.item(i));
				if(null != book)
					bookList.add(book);
			}
		}
		return bookList;
	}

	/**
	 * getting bookDTO from a Node
	 * @param node
	 * @return
	 */
	private BookDTO getDTOFromNode(Node node) {
		BookDTO book = null;
		if(null != node && node instanceof Element) {
			Element element = (Element)node;
			String name = element.getElementsByTagName("name").item(0).getTextContent();
			String price = element.getElementsByTagName("price").item(0).getTextContent();
			String author = element.getElementsByTagName("author").item(0).getTextContent();
			book = new BookDTO(name, author, price);
		}
		return book;
	}
	
}
